#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>

#define NLOOPS  1000
#define SIZE    sizeof(long)

extern void TELL_WAIT();
extern void WAIT_PARENT();
extern void TELL_PARENT(pid_t pid);
extern void WAIT_CHILD();
extern void TELL_CHILD(pid_t pid);

static int update(long *ptr)
{
    return ((*ptr)++);
}

int main(int argc, char *argv[])
{
    int i, counter, shmid;
    pid_t pid;
    void *area;

    if ((shmid = shmget(IPC_PRIVATE, SIZE, 0600)) < 0)
    {
        perror("shmget error");
        exit(0);
    }

    if ((area = shmat(shmid, NULL, 0)) == NULL)
    {
        perror("shmat error");
        exit(0);
    }

    TELL_WAIT();

    if ((pid = fork()) == 0)
    {
        for (i = 1; i < NLOOPS+1; i+=2)
        {
            WAIT_PARENT();

            if ((counter = update((long *)area)) != i)
            {
                fprintf(stderr, "child: expected %d, got %d\n", i, counter);
                exit(0);
            }

            TELL_PARENT(getppid());
        }
    }
    else
    {
        for (i = 0; i < NLOOPS; i+=2)
        {
            if ((counter = update((long *)area)) != i)
            {
                fprintf(stderr, "parent: expected %d, got %d\n", i, counter);
                exit(0);
            }

            TELL_CHILD(pid);
            WAIT_CHILD();
        }
    }

    return 0;
}
